package com.chain.qs.modules.biz.listener;


import com.chain.qs.common.mapper.JsonMapper;
import com.chain.qs.common.utils.CacheUtils;
import com.chain.qs.common.utils.CastUtils;
import com.chain.qs.common.utils.StringUtils;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 数据获取监听器(告警采集数据)
 * 从mq中获取
 */
@Component
public class WarningConsumerMessageListener implements MessageListener {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource
    private SimpMessagingTemplate msgTemplate;

    private TextMessage recievedMsg;

    private String json = "";

    public void onMessage(Message message) {
        recievedMsg = (TextMessage) message;
        try {
            json = recievedMsg.getText();
            logger.debug("This is receive jsonString : " + json);
        } catch (JMSException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        Map<String, String> map = CastUtils.convertToHashMapStringString(JsonMapper.fromJsonString(json, Map.class));
        httpSendMsg(map);
    }

    public void httpSendMsg(Map<String, String> dataMap) {
        Map<String, String> wsSessionMap = (Map<String, String>) CacheUtils.get("ws_sessions");
        wsSessionMap = (wsSessionMap == null ? Maps.newConcurrentMap() : wsSessionMap);
        Map<String, String> filteredDateMap = null;
        Object tmpMsgDate = "";
        if (wsSessionMap != null) {
            Set<String> set = wsSessionMap.keySet();
            Iterator<String> iterator = set.iterator();
            while (iterator.hasNext()) { //遍历根据用户进行推送
                String sessionId = iterator.next();
                String tmpCacheSessionStaionCode = wsSessionMap.get(sessionId);
                if (!StringUtils.isBlank(tmpCacheSessionStaionCode)) {
                    tmpMsgDate = dataMap.get(tmpCacheSessionStaionCode);
                    if (tmpMsgDate != null) {
                        this.msgTemplate.convertAndSend("topic/warning-user" + sessionId, dataMap);
                    }
                }
            }
        }
    }
}